package cn.tedu.boke.portal.service.impl;

import cn.tedu.boke.portal.mapper.UserMapper;
import cn.tedu.boke.portal.model.Permission;
import cn.tedu.boke.portal.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author Xdoor
 * @version 1.0
 * @date 2021/10/28 16:17
 */

@Component
public class UserDetailsServiceImpl implements UserDetailsService
{
    @Autowired
    private UserMapper userMapper;

    //下面的方法是接口提供的,我们来实现
    // 方法的参数是用户在登录表单编写的用户名
    //方法的返回值是UserDetails类型
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        User user = userMapper.findUserByUsername(username);

        if (user == null)
        {
            return null;
        }

        List<Permission> permissions = userMapper.findUserPermissionsById(user.getId());

        String[] auth = new String[permissions.size()];
        System.out.println("权限的个数为"+auth.length);
        int i = 0;
        for (Permission p : permissions)
        {
            System.out.println(p);
            auth[i] = p.getName();
            i++;
        }
        UserDetails details = org.springframework.security.core.userdetails.User.builder()
                .username(user.getUsername())//账号
                .password(user.getPassword())//密码
                .authorities(auth)//权限
                .accountLocked(user.getLocked() == 1) //设置当前账户是否锁定 false表示不锁定
                .disabled(user.getEnabled() == 0) //设置当前账户是否可用 false表示可用
                .build();

        return details;
    }
}
